from typing import Optional
from fastapi import BackgroundTasks, Depends, FastAPI
import uvicorn
import time
app = FastAPI()


def write_log(message: str):
    with open("log.txt", mode="a") as log:
        log.write(message)


def get_query(background_tasks: BackgroundTasks, q: Optional[str] = None):
    if q:
        message = f"found query: {q}\n"
        background_tasks.add_task(write_log, message)
    return q


@app.post("/send-notification/{email}")
async def send_notification(email: str, background_tasks: BackgroundTasks):
    message = f"message to {email}\n"
    background_tasks.add_task(write_log, message)
    return {"message": "Message sent"}


def task():
    print("1......")
    time.sleep(5)
    print("ok")


@app.post("/1")
async def crate(background_tasks: BackgroundTasks):
    s = time.time()
    background_tasks.add_task(task)
    # task()
    t = time.time() - s
    return {"success": True, "time": t}


@app.post("/2")
async def crate(background_tasks: BackgroundTasks):
    s = time.time()
    # task()
    t = time.time() - s
    return {"success": True, "time": t}

if __name__ == "__main__":
    uvicorn.run(app, host="0.0.0.0", port=8000)